//
//  CMDBPublishStatusViewController.swift
//  CMDB
//
//  Created by 曹桂祥 on 17/4/17.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

class CMDBPublishStatusViewController: CMDBBasePublishViewController {
    
    var textView : CMDBCommentView!
    
    var commentBtn : UIButton!
    
    private lazy var images : [UIImage] = [UIImage]()
    
    private var filePaths : NSMutableArray = NSMutableArray()
    
    private var qnUrls : [String] = [String]()
    
    private var mutable: NSMutableArray = NSMutableArray() // 这里存储的 CMDBImageParam
    
    private lazy var imagePickController: UIImagePickerController = {
        
        let imagePickController = UIImagePickerController()
        
        imagePickController.modalTransitionStyle = .CoverVertical
        
        return imagePickController
        
    }()
    
    private var selectedCollectionView: CMDBPublishPicsView? = CMDBPublishPicsView.getInstance()
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
        
    }
    
    override func buildTitleView() {
        super.buildTitleView()
        
        let button                    = UIButton(frame : CGRect(x: CMDB_Screen_Width - 140, y: 0, width: 100, height: 64))
        
        commentBtn                    = button
        
        button.center                 = CGPoint(x: CMDB_Screen_Width - 20, y: self.titleView!.middleY + 10)
        
        button.setTitle("发送", forState: .Normal)
        
        button.titleLabel?.font       = CMDB_16_FONT
        
        button.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
        
        button.enabled                = false
        
        self.titleView?.addSubview(button)
        
        button.addTarget(self, action: #selector(sendItemClick), forControlEvents: .TouchUpInside)
        
        
    }
    
    
    
    override func buildContentView() {
        
        super.buildContentView()
        
        textView          = CMDBCommentView(frame: CGRect(x: 0, y: 0, width: CMDB_Screen_Width, height: 0.35 * CMDB_Screen_Height))
        
        textView.delegate = self
        
        contentView?.addSubview(textView)
        
        buildSelectedCollectionView()
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}


extension CMDBPublishStatusViewController{
    
    func buildSelectedCollectionView(){
        
        selectedCollectionView?.mDelegate = self
        
        selectedCollectionView!.frame    = CGRect(x: 0, y: CGRectGetMaxY(self.textView.frame) + 5, width: CMDB_Screen_Width, height: (150 + 30) * CMDB_Rate * 3)
        
        contentView?.addSubview(selectedCollectionView!)
        
    }
}


extension CMDBPublishStatusViewController{
    
    // MARK:- 事件监听函数
    
    func test(){
        
        let dynamicParam = CMDBPubDynamicParam()
        
        dynamicParam.content = textView.text
        
        
        CMDBQNManager.getInstance.queryQNToken({ [weak self](token) in
            
            _ = self!.images.map({
                
                let qnParam = CMDBQNUploadParam()
                
                qnParam.qnToken = token
                
                qnParam.imageName = "pubs.png"

                qnParam.image = $0
                
                do {
                    
                    try CMDBQNManager.getInstance.uploadImageToQN(qnParam, progressHandler: { (percent, uploadStatus) in
                        
                        }, qnUrlHandler: { (qnUrl) in
                            
                            let imageParam = CMDBImageParam()
                            
                            imageParam.image = qnParam.image
                            
                            imageParam.url = qnUrl
                            
                            dynamicParam.upload_Images += [imageParam]
                            
                            do {
                                
                                try CMDBDynamicManager.getInstance.pubDynamic(dynamicParam, handler: { (dynamic) in
                                    
                                    
                                    
                                    }, error: { (rescode) in
                                        
                                    }, failure: {
                                        
                                })
                                
                            }catch{
                            
                            }
                    })
                    
                } catch {
                    
                    
                    
                    
                }
                
            })
            
            
            }, error: { (rescode) in
                
            }, faliure: {
                
        })
        
    }
    
    
    @objc private func sendItemClick() {
        
        printLog("send")
        
        test()
        
//        let dynamicParam       = CMDBPubDynamicParam()
//        
//        dynamicParam.content   = textView.text
//        
//        let uploadImageParam   = CMDBImageParam()
//        
//        uploadImageParam.image = images.first
//        
//        for (index,image) in images.enumerate() {
//            
//            let imageParam = CMDBImageParam()
//            
//            imageParam.image = image
//            
//            mutable.addObject(imageParam)
//        }
//        
//        dynamicParam.upload_Images = [uploadImageParam]
//        
//        let qnParam = CMDBQNUploadParam()
//        
//        let nameString = "statusPic_" + "\(0)" + "\(NSDate.timeStamp_ms())"
//        
//        filePaths.addObject(UIImage.getImagePath(images[0], imageName: nameString)!)
//        
//        qnParam.image = images[0]
//        
//        qnParam.imageName = nameString
//        
//        
//        do {
//            
//            try CMDBQNManager.getInstance.queryQNToken({ (token) in
//                
//                qnParam.qnToken = token
//                
//                do {
//                    
//                    try CMDBQNManager.getInstance.uploadImageToQN(qnParam, progressHandler: { (percent, uploadStatus) in
//                        
//                        }, qnUrlHandler: { (qnUrl) in
//                            self.qnUrls.append(qnUrl)
//                            
//                            uploadImageParam.url = qnUrl
//                            
//                            dynamicParam.upload_Images = [uploadImageParam]
//                            
//                            do {
//                                try CMDBDynamicManager.getInstance.pubDynamic(dynamicParam, handler: {[weak self] (dynamic) in
//                                    
//                                    
//                                    
//                                    self!.popSelf()
//                                    
//                                    }, error: { (rescode) in
//                                        
//                                    }, failure: {
//                                        
//                                })
//                            }
//                            catch{
//                                
//                            }
//                            
//                    })
//                    
//                }catch{
//                    
//                }
//                
//                
//                }, error: { (rescode) in
//                    
//                }, faliure: {
//                    
//            })
//            
//        }catch{
//            
//        }
    }
    
    
    
    
    @objc private func keyboardWillChangeFrame(note : NSNotification) {
        
    }
}

extension CMDBPublishStatusViewController : UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        self.textView.placeHolderLabel.hidden = textView.hasText()
        
        commentBtn.enabled                    = textView.hasText()
        
        commentBtn.setTitleColor(commentBtn.enabled ? UIColor.orangeColor() : UIColor.lightGrayColor(), forState: .Normal)
    }
    
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    
}

extension CMDBPublishStatusViewController{
    
    private func setupNotifications() {
        // 监听键盘的弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CMDBPublishStatusViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
}



extension CMDBPublishStatusViewController {
    
    override func onItemClickType(itemClickType: String?, data: AnyObject?, indexPath: NSIndexPath?) {
        
        let itemType = ItemClickType(string: itemClickType!)
        
        switch itemType {
            
        case .AddPhotoClick:
            
            textView.resignFirstResponder()
            
            if images.count == Max_selectedImages {
                let alertView = UIAlertView.init(title: "提示", message: "最多选择九张图片", delegate: nil, cancelButtonTitle: "知道了")
                
                alertView.show()
                
                return
            }
            
            let actionSheet = ACActionSheet(title: "选取照片",cancelButtonTitle: "取消",destructiveButtonTitle: nil,otherButtonTitles: ["从相册中选取","相机"],actionSheetBlock: {[weak self] (index) in
                switch index {
                case 0:
                    
                    self!.takePhoto()
                    
                    break
                case 1:
                    
                    self!.takeCamera()
                    
                    break
                    
                default:
                    
                    break
                }
                })
            
            actionSheet.show()
            break
        default :
            printLog("default")
        }
    }
    
}


// MARK:- UIImagePickerController的代理方法
extension CMDBPublishStatusViewController  {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        // 1.获取选中的照片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        
        
        // 2.将选中的照片添加到数组中
        images.append(image)
        
        
        
        // 3.将数组赋值给collectionView,让collectionView自己去展示数据
        selectedCollectionView!.images = images
        
        // 4.退出选中照片控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}


extension CMDBPublishStatusViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func takePhoto() {
        
        
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            return
        }
        
        // 3.设置照片源
        imagePickController.sourceType = .PhotoLibrary
        
        // 4.设置代理
        imagePickController.delegate = self
        
        // 弹出选择照片的控制器
        presentViewController(imagePickController, animated: true, completion: nil)
        
    }
    
    internal func takeCamera() {
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            
            imagePickController.delegate = self
            
            imagePickController.sourceType = .Camera
            
            presentViewController(imagePickController, animated: true, completion: nil)
            
        } else {
            
            print("模拟器中无法打开相机")
        }
        
        
    }
    
    
}
